package socket2;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class ServerDemo implements Runnable{
	public static void main(String[] args) {
		try {
			ServerSocket server=new ServerSocket(8899);
			System.out.println("服务器启动");
			System.out.println(server.getLocalPort());
			Socket socket=server.accept();
			System.out.println(socket.getPort());
			System.out.println("客户端连接");
			ObjectInputStream in=new ObjectInputStream(socket.getInputStream());
			String m;
			do{
				m=(String)in.readObject();//从网络接受客户端信息
				System.out.println("客户端说："+m);
			}while(!m.equals("bye"));
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("在同一台电脑上，只能运行一个实例");
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void run() {
		try {
			Socket socket=new Socket("192.168.1.115", 8899);
			System.out.println("已连接上服务器");
			Scanner in=new Scanner(System.in);
			String message;
			ObjectOutputStream out=new ObjectOutputStream(socket.getOutputStream());
			do{
				message=in.nextLine();
				out.writeObject(message);
				out.flush();
			}while(!message.equals("bye"));
			in.close();socket.close();
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 		
	}
}

